<template>
	<block>
	<uni-popup ref="popup" :is-mask-click="false" type="center" style="z-index:999;">
		<view class="relative" :style="`width:${canvasW}px;margin:${isInviteGroupBuy?'80rpx':'130rpx'} auto 0 auto;`">
			<view class="mb-6 flex justify-end w-full z-1" :class="{'absolute':isInviteGroupBuy}">
				<image class="size-26" src="@/static/svg/icon-close.svg" @click.stop="onClose"></image>
			</view>
			<view class="radius-8 overflow-auto flex justify-center">
				<canvas v-if="!isInviteGroupBuy" canvas-id="myPoster" :style="`width:${canvasW - decreaseW * 2}px;height:${canvasH}px;`"></canvas>
				<canvas v-else canvas-id="myPoster2" :style="`width:${canvasW - decreaseW * 2}px;height:${canvasH}px;`"></canvas>
			</view>
			<view class="flex item-center justify-between">
				<view class="w50 mt-12 h-46 bg-primary flex center radius-8 text-white fs-16 font-normal leading-22" @click.stop="saveImage">保存海报</view>
				<button v-if="!hasWritePhotosAlbumPermission" class="w50 mt-12 h-46 flex center radius-8 text-white fs-16 font-normal leading-22" style="background:#16BE62;" @click.stop="preSaveImage">分享好友</button>
				<button v-else-if="shareActiveData" open-type="share" data-share-type="activity" :data-activity-id="id" :data-title="shareActiveData.activeTitle" :data-share-code="shareActiveData.shareCode" 
					:data-filePath="getFirstImage(shareActiveData.activeImg)" :data-promotion-type="shareActiveData.promotionType" :data-ext-params="extParams"
					class="w50 mt-12 h-46 flex center radius-8 text-white fs-16 font-normal leading-22" style="background:#16BE62;">分享好友</button>
			</view>
			
			<!-- <button v-else-if="shareActiveData" data-share-type="activity" :data-activity-id="id" :data-title="shareActiveData.activeTitle" :data-filePath="tempFilePath" class="mt-12 h-46 flex center radius-8 text-white fs-16 font-normal leading-22" style="background:#16BE62;" @click="toShare">分享好友</button> -->
		</view>
	</uni-popup>
	</block>
</template>

/**
 * 活动分享
 */
<script setup name="ShareActivity">
	import { ref, computed, watchEffect, getCurrentInstance, onMounted, watch } from 'vue'
	import { useUserStore } from '@/stores/modules/user.js'
	import { useShare } from '@/hooks/useShare.js'
	import { usePermission } from '@/hooks/usePermission.js'
	import { drawRoundedRect, drawRoundImg, drawRoundImgfit, textPrewrap, getSystem } from '@/utils/canvasUtil.js'
	import { isVideoFile } from '@/utils/index.js'
	
	const userStore = useUserStore()
	const { preShareData, shareActiveData, getPreShare, getShareActivityData } = useShare()
	const { hasPermission } = usePermission()
	
	const props = defineProps({
		id: {
			type: [Number, String]
		},
		show: {
			type: Boolean
		},
		extParams:{
			type:Object,
		},
		type:{
			type:String,
			default:''
		},
		notPromotionIncentive:{ // 是否不需要选择积分佣金了
			type:Boolean,
			default: false
		},
		options:{ // 一些相关的配置
			type:Object,
		}
	})
	
	const emits = defineEmits(['onClose'])
	
	const instance = getCurrentInstance()
	
	const popup = ref(null)
	
	const getFirstImage = (activeImg) => {
		const arr = activeImg && activeImg.split(',') || []
		const imgPath = arr.find(path => !isVideoFile(path))
		return imgPath
	}
	
	const onClose = () => {
		popup.value && popup.value.close()
		emits('onClose')
	}
	
	const shareData = ref(null)
	
	const { w, h, scale } = getSystem()
	const dpr = uni.getSystemInfoSync().pixelRatio

	const isInviteGroupBuy = computed(()=>props.type==='inviteGroupBuy')

	const canvasId = computed(()=>isInviteGroupBuy.value?'myPoster2':'myPoster')

	// 长宽比 5:4  750:600  375:300
	const canvasW = 343 * scale
	const decreaseW = 12 * scale;
	const canvasH = computed(() => {
		return isInviteGroupBuy.value ? 642 * scale : 467 * scale;
	})
	// console.log('画布宽高', canvasW, canvasH)
	
	const draw = async () => {
		if(isInviteGroupBuy.value){
			drawForGroupBuy();
			return;
		}

		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		let drawY = 0
		const ctx = uni.createCanvasContext(canvasId.value, instance)
		// ctx.font = 'normal bold 14px PingFang SC,Arial,sans-serif'
		// 绘制渐变背景
		// let gradient = ctx.createCircularGradient(0, 0, canvasW)
		// gradient.addColorStop(0, '#F7D6D2')
		// gradient.addColorStop(1, 'white')
		// drawRoundedRect(ctx, 0, 0, canvasW, canvasH, {
		// 	leftTop: true,
		// 	leftBottom: true,
		// 	rightTop: true,
		// 	rightBottom: true,
		// 	fillColor: gradient,
		// 	r: 8 * scale,
		// })
		// let bgImg = await getImageInfo('https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/activity-bg.png')
		// drawRoundImg(ctx, bgImg.path, 0, 0, canvasW, canvasH.value, 0)
		drawRoundedRect(ctx, 0, 0, canvasW - decreaseW * 2, canvasH.value - 10, {
			leftTop: true,
			leftBottom: true,
			rightTop: true,
			rightBottom: true,
			fillColor: '#fff',
			r: 4 * scale,
		})

		// 商家logo
		const avatar = await getImageInfo(shareActiveData.value.logo)
		drawRoundImg(ctx, avatar.path, 41 * scale - decreaseW, 40 * scale, 32 * scale, 32 * scale, 16 * scale)
		// 商家昵称
		ctx.setFontSize(16 * scale)
		ctx.setFillStyle('#333')
		ctx.fillText((shareActiveData.value.businessShortName||'').replace(/\n/g,''), 80 * scale - decreaseW, 60 * scale, 300 * scale)
		
		// 首图
		const coverImg = await getImageInfo(getFirstImage(shareActiveData.value.activeImg))
		drawRoundImgfit(ctx, coverImg.path, coverImg.width, coverImg.height, 41 * scale - decreaseW, 84 * scale, 260 * scale, 173 * scale, 8 * scale)
		
		
		ctx.setFontSize(16 * scale)
		ctx.setFillStyle('#333')
		// 活动标题
		const lines = textPrewrap(ctx, shareActiveData.value.activeTitle, 41 * scale - decreaseW, 290 * scale, 22 * scale, 254 * scale, 2)
		
		drawY = 300 * scale + lines * scale + 22 * scale + 8 * scale
		ctx.setFontSize(14 * scale)
		ctx.setFillStyle('#FA4543')
		ctx.fillText('¥', 41 * scale - decreaseW, drawY + 15 * scale)
		const symbolW = ctx.measureText('¥').width
		ctx.setFontSize(21 * scale)
		ctx.setFillStyle('#FA4543')
		ctx.fillText(shareActiveData.value.activePrice, 41 * scale - decreaseW + symbolW, drawY + 15 * scale)
		
		if (props.options?.groupBuyLabel?.trim()) {
			// 拼团标志
			ctx.setFontSize(12 * scale)
			const groupBuyLabelW = ctx.measureText(props.options?.groupBuyLabel).width
			drawRoundedRect(ctx, 41 * scale - decreaseW, drawY + 30 * scale, (groupBuyLabelW + 6) * scale, 18 * scale, {
				leftTop: true,
				leftBottom: true,
				rightTop: true,
				rightBottom: true,
				fillColor: '#FBDBB0',
				r: 4 * scale,
			})
			ctx.setFillStyle('#333')
			ctx.fillText(props.options?.groupBuyLabel, 41 * scale + 3 * scale - decreaseW, drawY + (30 + 14) * scale)
		}
		
		drawY += 42 * scale
		
		ctx.setFontSize(12 * scale)
		drawRoundedRect(ctx, 41 * scale - decreaseW, drawY + 20 * scale, 171 * scale, 22 * scale, {
			leftTop: true,
			leftBottom: true,
			rightTop: true,
			rightBottom: true,
			fillColor: '#F5F5F5',
			r: 4 * scale,
		})
		ctx.setFillStyle('#727272')
		ctx.fillText('长按识别小程序 跟团购买', 41 * scale + 8 * scale - decreaseW, drawY + 12 * scale + 4 * scale + 20 * scale, 196 * scale)
		const arrowImg = await getImageInfo('https://admin.huodongtg.com/static/image/direction.png')
		drawRoundImg(ctx, arrowImg.path, 196 * scale - (arrowImg.width||20)/2 + 8 * scale - decreaseW, drawY + 22 * scale/2, 15 * scale, 10 * scale, 0)

		// 小程序码
		const codeImg = await getImageInfo(shareActiveData.value.miniImgUrl)
		drawRoundImg(ctx, codeImg.path, 225 * scale - decreaseW, drawY - 27 * scale + 20 * scale, 76 * scale, 76 * scale, 0)

		if(shareActiveData.value.posterShowAvatarState && shareActiveData.value.posterShowAvatarState === 1){
			const avatar = await getImageInfo(shareActiveData.value.logo)
			drawRoundImg(ctx, avatar.path, 246 * scale - decreaseW, drawY + 14 * scale, 34 * scale, 34 * scale, 17 * scale)
		}
		
		// 延迟渲染
		setTimeout(() => {
			ctx.draw(true, () => uni.hideLoading())
			preSaveImage(false)
		}, 500)
	}

	const drawForGroupBuy = async () => {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		let drawY = 0
		const ctx = uni.createCanvasContext(canvasId.value, instance)
		let bgImg = await getImageInfo('https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-share-bg.png')
		drawRoundImg(ctx, bgImg.path, 0, 0, canvasW - decreaseW * 2, canvasH.value, 0)
		
		// 商家logo
		const avatar = await getImageInfo(shareActiveData.value.logo)
		drawRoundImg(ctx, avatar.path, 41 * scale - decreaseW, 235 * scale, 32 * scale, 32 * scale, 16 * scale)
		// 商家昵称
		ctx.setFontSize(16 * scale)
		ctx.setFillStyle('#333')
		ctx.fillText((shareActiveData.value.businessShortName||'').replace(/\n/g,''), 80 * scale - decreaseW, 255 * scale, 300 * scale)

		// 首图
		const coverImg = await getImageInfo(getFirstImage(shareActiveData.value.activeImg))
		drawRoundImgfit(ctx, coverImg.path, coverImg.width, coverImg.height, 41 * scale - decreaseW, 280 * scale, 260 * scale, 173 * scale, 8 * scale)
		
		// // title
		ctx.setFontSize(16 * scale)
		ctx.setFillStyle('#333')
		const lines = textPrewrap(ctx, shareActiveData.value.activeTitle, 41 * scale - decreaseW, 480 * scale, 22 * scale, 254 * scale, 2)
		
		drawY = 478 * scale + lines * scale + 22 * scale + 8 * scale
		ctx.setFontSize(14 * scale)
		ctx.setFillStyle('#FA4543')
		ctx.fillText('¥', 41 * scale - decreaseW, drawY + 25 * scale) 
		const symbolW = ctx.measureText('¥').width
		ctx.setFontSize(21 * scale)
		ctx.setFillStyle('#FA4543')
		ctx.fillText(shareActiveData.value.activePrice, 41 * scale - decreaseW + symbolW, drawY + 25 * scale)

		if (props.options?.groupBuyLabel?.trim()) {
			// 拼团标志
			ctx.setFontSize(12 * scale)
			const groupBuyLabelW = ctx.measureText(props.options?.groupBuyLabel).width
			drawRoundedRect(ctx, 41 * scale - decreaseW, drawY + 35 * scale, (groupBuyLabelW + 6) * scale, 18 * scale, {
				leftTop: true,
				leftBottom: true,
				rightTop: true,
				rightBottom: true,
				fillColor: '#FBDBB0',
				r: 4 * scale,
			})
			ctx.setFillStyle('#333')
			ctx.fillText(props.options?.groupBuyLabel, 41 * scale + 3 * scale - decreaseW, drawY + (35 + 14) * scale)
		}
		
		drawY += 37 * scale
		
		ctx.setFontSize(12 * scale)
		// 跟团购买背景
		drawRoundedRect(ctx, 41 * scale - decreaseW, drawY + 30 * scale, 171 * scale, 22 * scale, {
			leftTop: true,
			leftBottom: true,
			rightTop: true,
			rightBottom: true,
			fillColor: '#F5F5F5',
			r: 4 * scale,
		})
		ctx.setFillStyle('#727272')
		ctx.fillText('长按识别小程序 跟团购买', 41 * scale - decreaseW + 8 * scale, drawY + 12 * scale + 4 * scale + 30 * scale, 196 * scale)
		
		// 小程序码
		const codeImg = await getImageInfo(shareActiveData.value.miniImgUrl)
		drawRoundImg(ctx, codeImg.path, 225 * scale - decreaseW, drawY - 27 * scale + 30 * scale, 76 * scale, 76 * scale, 0)

		if(shareActiveData.value.posterShowAvatarState && shareActiveData.value.posterShowAvatarState === 1){
			const avatar = await getImageInfo(shareActiveData.value.logo)
			drawRoundImg(ctx, avatar.path, 246 * scale - decreaseW, drawY + 24 * scale, 34 * scale, 34 * scale, 17 * scale)
		}
		
		// 延迟渲染
		setTimeout(() => {
			ctx.draw(true, () => uni.hideLoading())
			preSaveImage(false)
		}, 500)
	}

	//获取图片
	const getImageInfo = (imgSrc) => {
		if (!imgSrc) return Promise.reject('空地址')
		return new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: imgSrc,
				success: (image) => {
					resolve(image);
					// console.log('获取图片成功',image)
				},
				fail: (err) => {
					reject(err);
					console.log('获取图片失败',err, imgSrc)
					uni.hideLoading()
				}
			})
		})
	}

	const hasWritePhotosAlbumPermission = ref(false)
	const saveImage = async () => {
		//判断用户授权
		const res = await hasPermission('scope.writePhotosAlbum', true, '请授权添加到相册权限')
		hasWritePhotosAlbumPermission.value = res
		if (!res) {
			return
		}
		uni.canvasToTempFilePath({
			canvasId: canvasId.value,
			quality: 1,
			complete: (res) => {
				// console.log('保存到相册',res);
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success(res) {
						uni.showToast({
							title: '已保存到相册',
							icon: 'success',
							duration: 2000
						})
						setTimeout(()=>{
							onClose()
						},2000)
					}
				})
			}
		},instance);
	}
	
	const toShare = () => {
		uni.showShareImageMenu({
			path: tempFilePath.value,
			name: shareActiveData.value.activeTitle +'.png',
			success() {},
			fail: console.error,
		})
	}
	const handlePromotionInterset = () => {
		getShareActivityData(props.id, props.extParams).then(res => {
			shareData.value = res
			popup.value && popup.value.open()
			draw()
		})
	}
	
	watchEffect(() => {
		if (props.show && props.id) {
			handlePromotionInterset()
		}
	})
	
	const tempFilePath = ref('')
	const preSaveImage = async (openSetting = true) => {
		//判断用户授权
		const res = await hasPermission('scope.writePhotosAlbum', openSetting, '请授权添加到相册权限')
		hasWritePhotosAlbumPermission.value = res
		if (!res) {
			return
		}
		uni.canvasToTempFilePath({
			canvasId: canvasId.value,
			quality: 1,
			complete: (res) => {
				tempFilePath.value = res.tempFilePath
			}
		}, instance)
	}
	onMounted(()=>{
		console.log(props);
	})
</script>

